﻿Module Module1

    Public results(100000) As Decimal


    Sub Main()
        Dim coresInComputer As Integer = Environment.ProcessorCount
        Dim threader As New ThreadBalance()
        Dim stopWatch As New Stopwatch()
        Console.WriteLine("Number Of logical processors found: " & coresInComputer)
        stopWatch.Reset()
        stopWatch.Start()
        For index As Integer = 0 To results.Count - 1
            For l As Integer = 1 To 500
                Dim calculation = Math.Sin(index / 180.0 * Math.PI) * Math.Cos(index / 180.0 * Math.PI) + l
                results(index) = calculation
            Next
        Next
        stopWatch.Stop()
        Dim ts As TimeSpan = stopWatch.Elapsed
        Dim elapsedTime As String = String.Format("{0:0}.{1:00}", ts.Seconds, ts.Milliseconds / 10)
        Console.WriteLine(elapsedTime & " seconds, unthreaded.")

        For threads As Integer = 1 To coresInComputer + 2 ' Go over a bit to see the effect.
            Dim coresUsed = If(threads < coresInComputer, threads, coresInComputer)
            Console.Write("Run using " & threads & " thread" & If(threads <> 1, "s", "") & " on " & coresUsed & " core" & If(threads <> 1, "s", "") & ": ")
            For runNumber As Integer = 1 To 3
                stopWatch.Reset()
                stopWatch.Start()
                'Don't specify threads(cores) to make runThreads use the maximum available.
                'e.g:
                'threader.runThreads(AddressOf calculate, results.Count)
                threader.runThreads(AddressOf calculate, results.Count, threads)
                stopWatch.Stop()
                ts = stopWatch.Elapsed
                elapsedTime = String.Format("{0:0}.{1:00}", ts.Seconds, ts.Milliseconds / 10)
                Console.Write(elapsedTime & " secs" & If(runNumber = 3, "." & vbCrLf, ", "))
            Next
        Next
        Console.WriteLine("All done!")
        Console.WriteLine("Notice how it's slower when we start using more threads than cores.")
        Console.ReadKey()
    End Sub

    Public Sub calculate(ByVal startIndex As Integer, ByVal endIndex As Integer)
        For index As Integer = startIndex To endIndex
            For l As Integer = 1 To 500
                Dim calculation = Math.Sin(index / 180.0 * Math.PI) * Math.Cos(index / 180.0 * Math.PI) + l
                results(index) = calculation
            Next
        Next
    End Sub

End Module
